<template>
  <div class="login-forget">
    <!-- 顶部标题 -->
    <div class="controls">
      <el-link type="primary" @click="forgetHandle">
        <el-icon><ArrowLeftBold /></el-icon> 返回
      </el-link>
    </div>
    <h1 class="title">忘记密码</h1>
    <!-- 中间的表单 -->
    <div class="form">
      <el-form
        :model="account"
        :rules="rules"
        label-width="80px"
        size="large"
        status-icon
        ref="ruleFormRef"
      >
        <el-form-item label="注册邮箱" prop="userEmail">
          <el-input v-model="account.userEmail" />
        </el-form-item>
        <el-form-item label="新密码" prop="password">
          <el-input v-model="account.password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="again">
          <el-input v-model="account.again" show-password />
        </el-form-item>
        <el-form-item label="验证码" prop="verify">
          <div class="send-verify">
            <el-input v-model="account.verify" />
            <el-button
              type="primary"
              style="margin-left: 10px"
              :loading="isLoading"
              @click="sendButHendal(ruleFormRef)"
              >{{ loadingMeg }}</el-button
            >
          </div>
        </el-form-item>
        <el-form-item>
          <el-button class="login-btn" type="primary" size="large" @click="submitForm(ruleFormRef)"
            >重置密码</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, defineProps } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormRules, ElForm, FormInstance } from 'element-plus'
import { getVCode } from '@/service/email/email'
const props = defineProps(['forget'])
const emit = defineEmits(['forgetHandle', 'resetPassword'])
//1. 定义account数据
interface IAccount {
  userEmail: string
  password: string
  again: string
  verify: string
}
//单独定义验证码
const myVerify = ref('')
const ruleFormRef = ref<FormInstance>()

//设置一分钟只能发送一次验证码
const isLoading = ref(false)
const loadingMeg = ref('发送验证码')
let t1: NodeJS.Timer
let time: number = 60

//确认密码的校验
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('请再次输入密码！'))
  } else {
    if (value !== account.password) {
      callback(new Error('两次密码不相同！'))
    } else {
      callback()
    }
  }
}
const account = reactive<IAccount>({
  userEmail: '',
  again: '',
  password: '',
  verify: ''
})

const validateVerify = (rule: any, value: any, callback: any) => {
  if (myVerify.value == '' || value !== myVerify.value) {
    callback(new Error('验证码错误！'))
  }
  callback()
}
//2. 定义校验规则，并绑定函数
const rules = reactive<FormRules<typeof account>>({
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: /^([a-zA-Z]|[0-9])(\w|\\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
      message: '请正确输入邮箱',
      trigger: 'change'
    },
    {
      pattern: /^([a-zA-Z]|[0-9])(\w|\\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/,
      message: '请正确输入邮箱',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码信息', trigger: 'blur' },
    {
      pattern: /^(?![a-zA-Z]+$)(?!\d+$)(?![^\da-zA-Z\s]+$).{9,}$/,
      message: '密码至少由9位以上字母、数字、特殊字符组成',
      trigger: 'change'
    },
    {
      pattern: /^(?![a-zA-Z]+$)(?!\d+$)(?![^\da-zA-Z\s]+$).{9,}$/,
      message: '密码至少由9位以上字母、数字、特殊字符组成',
      trigger: 'blur'
    }
  ],
  again: [{ required: true, validator: validatePass2, trigger: 'change' }],
  verify: [
    {
      required: true,
      validator: validateVerify,
      trigger: 'blur'
    }
  ]
})
//重置密码
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    //表单校验成功
    if (valid) {
      const { password, userEmail } = account
      emit('resetPassword', { password, userEmail })
      forgetHandle()
    } else {
      ElMessage.error('请正确填写信息！')
    }
  })
}

//发送验证码的点击事件
const sendButHendal = (ruleFormRef: any) => {
  //发送验证码之前对邮箱进行校验
  ruleFormRef.validateField('userEmail', (errorMessage: any) => {
  if (errorMessage == true) sendVCode()
  })
  if (isLoading.value == false) {
    isLoading.value = true
    loadingMeg.value = time + '后再试'
    t1 = setInterval(() => {
      time--
      loadingMeg.value = time + '后再试'
      if (time == 0) {
        loadingMeg.value = '发送验证码'
        isLoading.value = false
        time = 2
        clearInterval(t1)
      }
    }, 1000)
  }
}

//发送验证码
const sendVCode = () => {
  getVCode({ userEmail: account.userEmail })
    .then((e: any) => {
      myVerify.value = e.data
      ElMessage({ type: 'success', message: '发送成功！' })
    })
    .catch((e: any) => {
      ElMessage({ type: 'success', message: '发送验证码失败' })
    })
}

//返回
const forgetHandle = () => {
  emit('forgetHandle')
}
</script>

<style lang="less" scoped>
.login-forget {
  width: 340px;
  border: 1px solid #fff;
  border-radius: 9px;
  background-color: #fff;
  box-shadow: 0 0 90px rgba(255, 255, 255, 0.5) inset;
  padding: 40px 50px 40px 10px;
  z-index: 999;

  .title {
    text-align: center;
    margin-left: 40px;
    margin-bottom: 25px;
  }
  .controls {
    margin-top: -20px;
    margin-bottom: 20px;
  }
  .login-btn {
    text-align: center;
    margin-top: 15px;
    margin-left: 15%;
    width: 50%;
    letter-spacing: 2px;
  }
  .send-verify {
    display: flex;
  }
}
</style>
